package com.gzy.net_app.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.google.gson.Gson;
import com.gzy.net_app.adapter.FaceAdapter;
import com.gzy.net_app.api.ApiService;
import com.gzy.net_app.application.AppContext;
import com.gzy.net_app.bean.FaceBean;
import com.gzy.net_app.databinding.ActivityFaceDetectionBinding;
import com.gzy.net_app.ui.BaseActivity;
import com.gzy.network.NetworkApi;
import com.gzy.network.observer.BaseObserver;
import com.gzy.network.utils.KLog;
import com.orhanobut.hawk.Hawk;
import java.io.File;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.json.JSONException;
import org.json.JSONObject;

public class FaceDetectionActivity extends BaseActivity<ActivityFaceDetectionBinding> {

  private static final int REQUEST_CODE = 10000;//权限
  private static final int TAKE_PHOTO = 11;// 拍照
  private static final int LOCAL_CROP = 13;// 本地图库

  public final String TAG = this.getClass().getSimpleName();

  String currentFileUrl = "";

  private FaceAdapter faceAdapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    faceAdapter = new FaceAdapter(this);
    //android版本在6.0以上
    if (Build.VERSION.SDK_INT >= 23) {
      System.out.println("版本正确");
      checkPermission();
    } else {
      System.out.println("版本过低");
    }


    binding.settingReturn.setOnClickListener(view -> finish());
    binding.btnChoosePicture.setOnClickListener(view -> getPhoto());
    binding.btnIdentifyPicture.setOnClickListener(view -> identifyFacePhoto());
  }

  // private void LogoutUser() {
  //   Hawk.delete("token");
  //   Intent intent = new Intent(FaceDetectionActivity.this, LoginActivity.class);
  //   startActivity(intent);
  // }

  //获取人脸照片
  private void getPhoto() {
    CharSequence[] items = { "拍照", "图库" };// 裁剪items选项
    // 弹出对话框提示用户拍照或者是通过本地图库选择图片
    new AlertDialog.Builder(this)
        .setItems(items, new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {

            switch (which) {
              // 选择了拍照
              case 0:
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, TAKE_PHOTO);
                break;
              // 调用系统图库
              case 1:
                // 创建Intent，用于打开手机本地图库选择图片
                Intent intent1 = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 启动intent打开本地图库
                startActivityForResult(intent1, LOCAL_CROP);
                break;
            }
          }
        }).show();
  }

  /**
   * 调用startActivityForResult方法启动一个intent后，
   * 可以在该方法中拿到返回的数据
   */
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
      case TAKE_PHOTO:// 拍照
        if (resultCode == RESULT_OK) {
          final Bitmap photo = data.getParcelableExtra("data");
          //将bitmap照片放入系统相册，并将照片给url
          currentFileUrl = AppContext.saveImageToGallery(this, photo);
          binding.ivFacepicture.setImageBitmap(photo);
          Log.d(TAG, "onActivityResult: " + currentFileUrl);
        }
        break;
      case LOCAL_CROP:// 系统图库
        if (resultCode == RESULT_OK) {
          Uri uri = data.getData();
          binding.ivFacepicture.setImageURI(uri);
          currentFileUrl = AppContext.getRealPathFromURI(this, uri);
          Log.d(TAG, "onActivityResult: " + currentFileUrl);
        }
        break;
    }
  }

  private void identifyFacePhoto() {
    if (TextUtils.isEmpty(currentFileUrl)) {
      AppContext.showToast("请先选择人脸照片");
      return;
    } else {
      binding.progressBar.setVisibility(View.VISIBLE);
      File file = new File(currentFileUrl);
      MultipartBody.Part part = MultipartBody.Part.createFormData("image",
          file.getName(),
          RequestBody.create(MediaType.parse("image/*"),
              file));

      RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "" + Hawk.get("token"));
      NetworkApi.createService(ApiService.class)
          .uploadFacePhoto2(part, body)
          .compose(NetworkApi.applySchedulers(new BaseObserver<ResponseBody>() {
            @Override public void onSuccess(ResponseBody responseBody) {
              String result = AppContext.doJson(responseBody);
              String face_list = null;
              FaceBean.ResultBean faceListBean = null;
              try {
                JSONObject jsonObject = new JSONObject(result);
                face_list = jsonObject.getString("result");
                KLog.d(TAG, face_list);
                Gson gson = new Gson();
                faceListBean = gson.fromJson(String.valueOf(new JSONObject(face_list)), FaceBean.ResultBean.class);
              } catch (JSONException e) {
                e.printStackTrace();
              }
              if (faceListBean != null) {
                showListFace(faceListBean);
                // binding.tvIdentifyFaceRusult.setText(AppContext.doJson(responseBody));
              } else {
                AppContext.showToast("识别返回接口数据为空");
                KLog.d(TAG, "识别返回接口数据为空");

                binding.progressBar.setVisibility(View.GONE);
              }
            }



            @Override public void onFailure(Throwable e) {

              binding.progressBar.setVisibility(View.GONE);
              KLog.d(TAG, e.toString());
              AppContext.showToast("此功能也被合并");
            }
          }));
    }
  }
  
  //测试了一下

  //展示泪飙
  private void showListFace(FaceBean.ResultBean faceListBean) {
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    binding.ryFacePeople.setLayoutManager(layoutManager);
    binding.ryFacePeople.setAdapter(faceAdapter);

    binding.progressBar.setVisibility(View.GONE);
    faceAdapter.updateFaceList(faceListBean.getFace_list());
  }

  private void checkPermission() {
    ActivityCompat.requestPermissions(FaceDetectionActivity.this,
        new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE },
        REQUEST_CODE);
  }

  @Override
  public void onRequestPermissionsResult(int requestCode,
                                         String permissions[], int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
      //权限的申请结果返回
      case REQUEST_CODE: {
        if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          //已授权
          AppContext.showToast("授权成功");
        } else {
          //未授权
          AppContext.showToast("授权被拒绝");
        }
      }
    }
  }

  @Override public void onBackPressed() {
    super.onBackPressed();
    finish();
  }
}